﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web.Mvc;
using PortalCurriculo.Domain;
using PortalCurriculo.MvcWebUI.Helpers;
using PortalCurriculo.MvcWebUI.Models;

namespace PortalCurriculo.MvcWebUI.Controllers
{
    public class CargoCurriculoController : ControllerBase<CargoCurriculoModel, CargoCurriculo>
    {
        public ActionResult MasterEdicao(int? idCurriculo)
        {
            if (!idCurriculo.HasValue) return PartialView();
            ViewBag.IdCurriculo = idCurriculo.Value;

            return PartialView(SelecionarCargos(idCurriculo.Value));
        }

        private static IEnumerable<CargoCurriculoModel> SelecionarCargos(int idCurriculo)
        {
            var cargos = new CargoCurriculo().SelecionarPorIdCurriculo(idCurriculo);
            return new CargoCurriculoModel().CriarViewModel(cargos);
        }

        [UserAuthorize(UserType = UserAuthorizeAttribute.UserTypes.Profissional)]
        public ActionResult Registro(int? id, int? idCurriculo)
        {
            if (id == 0) id = null;
            base.Manter(id);

            if (Model != null)
            {
                ViewBag.IdCurriculo = Model.IdCurriculo;
                ViewBag.Id = Model.Id;
            }
            else
                ViewBag.IdCurriculo = idCurriculo.Value;

            return PartialView();
        }

        [UserAuthorize(UserType = UserAuthorizeAttribute.UserTypes.Profissional)]
        public ActionResult Adicionar(FormCollection collection)
        {
            var model = new CargoCurriculoModel
                            {
                                IdCargo = int.Parse(collection.Get("Cargos")),
                                IdCurriculo = int.Parse(collection.Get("IdCurriculo")),
                                Id = string.IsNullOrEmpty(collection.Get("Id")) ? 0 : int.Parse(collection.Get("Id")),
                            };

            if (model.Id == 0 && new CargoCurriculo().Existe(model.IdCurriculo, model.IdCargo))
                throw new DuplicateNameException(Resources.Curriculo.Geral.CargoPretendidoDuplicado);

            base.Manter(model);

            return PartialView("Listar", SelecionarCargos(model.IdCurriculo));
        }

        [UserAuthorize(UserType = UserAuthorizeAttribute.UserTypes.Profissional)]
        public ActionResult Excluir(int id)
        {
            var model = new CargoCurriculo().SelectById<CargoCurriculo>(id);
            model.Delete<CargoCurriculo>(id);

            return PartialView("Listar", SelecionarCargos(model.IdCurriculo));
        }
    }
}
